<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\model;

/**
 * 系统公告模型
 */
class Announcement extends ModelBase
{
    // 公告类型常量
    const TYPE_SYSTEM = 'system';      // 系统公告
    const TYPE_COMMON = 'common';      // 普通公告
    const TYPE_NOTICE = 'notice';      // 通知公告
    const TYPE_ACTIVITY = 'activity';    // 活动公告
    const TYPE_MAINTENANCE = 'maintenance'; // 维护公告
    const TYPE_UPDATE = 'update';      // 更新公告
    
    // 公告状态常量（使用announcement_status字段）
    const ANNOUNCEMENT_STATUS_DRAFT = 0;      // 草稿
    const ANNOUNCEMENT_STATUS_PUBLISHED = 1;  // 已发布
    const ANNOUNCEMENT_STATUS_OFFLINE = 2;    // 已下线
    
    // 保留旧常量以兼容现有代码（已废弃，请使用ANNOUNCEMENT_STATUS_*）
    const STATUS_DRAFT = 0;      // 草稿
    const STATUS_PUBLISHED = 1;  // 已发布
    const STATUS_OFFLINE = 2;    // 已下线
    
    /**
     * 获取公告类型选项
     */
    public static function getTypeOptions()
    {
        return [
            self::TYPE_SYSTEM => '系统公告',
            self::TYPE_COMMON => '普通公告',
            self::TYPE_NOTICE => '通知公告',
            self::TYPE_ACTIVITY => '活动公告',
            self::TYPE_MAINTENANCE => '维护公告',
            self::TYPE_UPDATE => '更新公告',    
        ];
    }
    
    /**
     * 获取状态选项
     */
    public static function getStatusOptions()
    {
        return [
            self::STATUS_DRAFT => '草稿',
            self::STATUS_PUBLISHED => '已发布',
            self::STATUS_OFFLINE => '已下线',
        ];
    }
    
    /**
     * 获取公告类型文本
     */
    public function getTypeTextAttr($value = null, $data = [])
    {
        $options = self::getTypeOptions();
        return $options[$data['type']] ?? '未知';
    }
    
    /**
     * 获取状态文本
     */
    public function getStatusTextAttr($value = null, $data = [])
    {
        $options = self::getStatusOptions();
        return $options[$data['announcement_status']] ?? '未知';
    }
    
    /**
     * 获取已发布的公告列表
     * @param int $type 公告类型，0表示所有类型
     * @param int $limit 限制数量，0表示不限制
     * @return array
     */
    public function getPublishedAnnouncementList($type = 0, $limit = 0)
    {
        $where = ['announcement_status' => self::ANNOUNCEMENT_STATUS_PUBLISHED];
        
        // 添加类型条件
        if ($type > 0) {
            $where['type'] = $type;
        }
        
        // 只显示已发布的公告
        $where[] = ['publish_time', '<=', date('Y-m-d H:i:s')];
        
        $field = 'id,title,content,image_url,type,publish_time,sort';
        $order = 'sort DESC, publish_time DESC, id DESC';
        
        if ($limit > 0) {
            $result = $this->getList($where, $field, $order, $limit);
            return $result ?? [];
        } else {
            return $this->getList($where, $field, $order, false);
        }
    }
    
    /**
     * 获取最新公告
     * @param int $limit 限制数量，默认1条
     * @return array
     */
    public function getLatestAnnouncementList($limit = 1)
    {
        return $this->getPublishedAnnouncementList(0, $limit);
    }
    
    /**
     * 获取系统公告列表
     * @param int $limit 限制数量，默认10条
     * @return array
     */
    public function getSystemAnnouncementList($limit = 10)
    {
        return $this->getPublishedAnnouncementList(self::TYPE_SYSTEM, $limit);
    }
    
    /**
     * 获取活动公告列表
     * @param int $limit 限制数量，默认10条
     * @return array
     */
    public function getActivityAnnouncementList($limit = 10)
    {
        return $this->getPublishedAnnouncementList(self::TYPE_ACTIVITY, $limit);
    }
    
    /**
     * 获取维护公告列表
     * @param int $limit 限制数量，默认10条
     * @return array
     */
    public function getMaintenanceAnnouncementList($limit = 10)
    {
        return $this->getPublishedAnnouncementList(self::TYPE_MAINTENANCE, $limit);
    }
    
    /**
     * 获取公告详情（包含阅读状态）
     * @param int $id 公告ID
     * @param int $userId 用户ID，用于查询阅读状态
     * @return array|null
     */
    public function getAnnouncementDetail($id, $userId = 0)
    {
        $where = [
            'id' => $id,
            'announcement_status' => self::ANNOUNCEMENT_STATUS_PUBLISHED
        ];
        
        $announcement = $this->getInfo($where);
        if (empty($announcement)) {
            return null;
        }
        
        // 如果提供了用户ID，查询阅读状态
        if ($userId > 0) {
            $readModel = new AnnouncementRead();
            $readInfo = $readModel->getInfo([
                'announcement_id' => $id,
                'user_id' => $userId
            ]);
            $announcement['is_read'] = !empty($readInfo);
            $announcement['read_time'] = $readInfo['read_time'] ?? '';
        }
        
        return $announcement;
    }
    
    /**
     * 发布公告
     * @param int $id 公告ID
     * @return bool
     */
    public function publishAnnouncement($id)
    {
        $data = [
            'announcement_status' => self::ANNOUNCEMENT_STATUS_PUBLISHED,
            'publish_time' => date('Y-m-d H:i:s')
        ];
        
        return $this->updateInfo(['id' => $id], $data);
    }
    
    /**
     * 下线公告
     * @param int $id 公告ID
     * @return bool
     */
    public function offlineAnnouncement($id)
    {
        return $this->updateInfo(['id' => $id], ['announcement_status' => self::ANNOUNCEMENT_STATUS_OFFLINE]);
    }
    
    /**
     * 更新公告排序
     * @param int $id 公告ID
     * @param int $sortOrder 排序值
     * @return bool
     */
    public function updateSortOrder($id, $sortOrder)
    {
        return $this->updateInfo(['id' => $id], ['sort' => $sortOrder]);
    }
    
    /**
     * 获取用户未读公告数量
     * @param int $userId 用户ID
     * @return int
     */
    public function getUnreadCount($userId)
    {
        if ($userId <= 0) {
            return 0;
        }
        
        // 获取所有已发布的公告ID
        $publishedIds = $this->getColumn([
            'announcement_status' => self::ANNOUNCEMENT_STATUS_PUBLISHED,
            ['publish_time', '<=', date('Y-m-d H:i:s')]
        ], 'id');
        
        if (empty($publishedIds)) {
            return 0;
        }
        
        // 获取用户已读的公告ID
        $readModel = new AnnouncementRead();
        $readIds = $readModel->getColumn(['user_id' => $userId], 'announcement_id');
        
        // 计算未读数量
        $unreadIds = array_diff($publishedIds, $readIds);
        return count($unreadIds);
    }
}
